import { reqUserGegister, reqGetCode } from "@/api/register";
import { reqUserLogin, reqUserInfo, reqLogOut } from "@/api/login";
import { setToken, getToken, removeToken } from "@/until/token";
const state = {
  code: "", //验证码
  token: getToken(),
  userInfo: {},
};
const mutations = {
  //获取验证码
  GETCODE(state, code) {
    state.code = code;
  },
  //用户登录
  USERLOGIN(state, token) {
    state.token = token;
  },
  //获取用户信息
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  //退出登录
  USERLOGOUT(state) {
    state.userInfo = {};
    state.token = "";
    removeToken();
  },
};
const actions = {
  //获取验证码
  async getCode({ commit }, phone) {
    let res = await reqGetCode(phone);
    if (res.code == 200) {
      commit("GETCODE", res.data);
    }
  },
  //用户注册
  async userRegister({ commit }, registerData) {
    let res = await reqUserGegister(registerData);
    // console.log(res);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //用户登录
  async userLogin({ commit }, loginData) {
    let res = await reqUserLogin(loginData);
    // console.log(res);
    if (res.code == 200) {
      commit("USERLOGIN", res.data.token);
      //本地存储token
      setToken(res.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //获取用户信息
  async getUserInfo({ commit }) {
    let res = await reqUserInfo();
    // console.log(res);
    if (res.code == 200) {
      commit("GETUSERINFO", res.data);
      return "ok";
    } else {
      throw new Error("fail");
    }
  },
  //退出登录
  async userLogOut({ commit }) {
    let res = await reqLogOut();
    if (res.code == 200) {
      commit("USERLOGOUT");
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
};
const getters = {};
export default {
  state,
  mutations,
  actions,
  getters,
};
